/**
 * 15-600: Java and J2EE
 * Instructor: Jeff Eppinger
 * Done By:	Mohammad al Khani
 * Date Dec 10, 2011
 */

package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import model.Model;
import model.UserDAO;

import org.mybeans.form.FormBeanFactory;

import dataBeans.User;
import formBean.ChangePasswordForm;

public class ChangePasswordAction extends Action{

	private FormBeanFactory<ChangePasswordForm> formBeanFactory = FormBeanFactory.getInstance(ChangePasswordForm.class);
	private UserDAO userDAO;
	
	public ChangePasswordAction(Model model){
		userDAO = model.getUserDAO();
	}
	
	public String getName(){ 
		return "changePassword.do"; 
	}
    
    public String perform(HttpServletRequest request) {
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        
        try {
	    	ChangePasswordForm form = formBeanFactory.create(request);
	        
	    	request.setAttribute("form",form);
	        if(!form.isPresent()){
	        	return "changePassword.jsp";
	        }
	        
	        errors.addAll(form.getValidationErrors());
	        if(errors.size() > 0){
	        	return "changePassword.jsp";
	        }
	        
	        User currentUser = (User)request.getSession().getAttribute("user");
	        if(currentUser == null){
	        	errors.add("The user isn't there");
	        	return "error.jsp";
	        }
	        System.out.println("Trying to change password");
	        userDAO.changePassword(currentUser.getUserId(), form.getPassword());
	        errors.add("Password changed");
	        return "changePassword.jsp";
	        
        }catch(Exception e){
        	e.printStackTrace();
        	return "error.jsp";
        }
    }
}
